#coding:utf-8
from collections import Counter
from django.http import Http404
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from django_user_agents.utils import get_user_agent
from django.http.response import HttpResponseRedirect
from lovewith.analytics.views.modules.analyticsapi import ShopAnalyticsApi
from lovewith.supplier.views.modules.supplierapi import SupplierApi
from lovewith.views import site_info
from lovewith.share.views.modules.share import ShareApi
from lovewith.share.views.modules.attach import AttachApi
from lovewith.website.views.modules.category import CategoryApi
from lovewith.website.views.modules.color import ColorApi


#判断是否有编辑权限
def check_edit_role(post_user_id, user):
    if user.is_authenticated():
        if post_user_id == user.id or user.is_admin:
            return True
    return False


#单张图片页面
def get_single_detail(request, share_id):
    #判断UA
    user_agent = get_user_agent(request)
    #基础数据
    share_data = ShareApi.check_data(share_id)
    #图片id
    image_id = request.GET.get('mid')
    #图片数据
    image_data = AttachApi.check_data(image_id)

    if not share_data or not image_data or share_data.is_delete:
        raise Http404

    if user_agent.is_mobile:
        #图片相关数据
        image_ext_data = AttachApi().get_ext_data(image_id)
        #所有图片
        all_image_data = AttachApi.get_by_share(share_id)
        #封面
        cover_data = AttachApi.get_cover_attach(share_id)
        return render_to_response('mobile/detail-single.jinja', {
            'cates': CategoryApi.get_all(),
            'colors': ColorApi.get_all(),
            'share': share_data,
            'image_data': image_data,
            'image_ext_data': image_ext_data,
            'all_images': all_image_data,
            'cover_data': cover_data,
        }, context_instance=RequestContext(request, processors=[site_info]))
    else:
        return HttpResponseRedirect('/share/detail/all/%s/#m%s' % (image_data.share_post.id, image_data.id))


#完整detail
#@cache_page(60 * 15)
def get_full_detail(request, share_id):
    #判断UA
    user_agent = get_user_agent(request)
    share_data = ShareApi.check_data(share_id)

    if not share_data or share_data.is_delete:
        raise Http404

    #阅读数+1
    share_data.views += 1
    share_data.save()
    #由服务商提供的作品，统计数据+1
    if share_data.user.group_id == 3:
        supplier_data = SupplierApi.check_data(user_id=share_data.user_id)
        if supplier_data:
            ShopAnalyticsApi.increase(supplier_data)

    all_image_data = AttachApi.get_by_share(share_id)
    #没有图片
    if not all_image_data.exists():
        #删除帖子
        ShareApi.delete(share_data)
        #跳转到首页
        return HttpResponseRedirect('/')

    #封面
    cover_data = AttachApi.get_cover_attach(share_id)
    images_result = []
    keyword_data = []

    for img in all_image_data:
        image_data = ShareApi.get_ext_data(img.id)
        #图片标签
        tags = image_data['tags']
        #sale
        sale_data = image_data['taoke_data']

        images_result.append({
            'id': img.id,
            'path': img.path,
            'is_cover': img.is_cover,
            'like': img.like,
            'share_post_id': img.share_post.id,
            'tags': tags,
            'sale_data': sale_data
        })

        keyword_data.extend(tags)

    #来源标注
    origin_data = ShareApi.get_origin(share_data.id)

    keyword = Counter(keyword_data).keys()[:3]

    if user_agent.is_mobile:
        return render_to_response('mobile/detail-full.jinja', {
            'cates': CategoryApi.get_all(),
            'colors': ColorApi.get_all(),
            'share': share_data,
            'images': images_result,
            'cover_data': cover_data,
            'origin': origin_data,
        }, context_instance=RequestContext(request, processors=[site_info]))
    else:
        edit_enable = check_edit_role(share_data.user.id, request.user)
        #猜你喜欢
        guess_data = ShareApi.get_by_cate(share_data.cate.id, 1, content_type='selected')

        supplier_data = SupplierApi.check_data(user_id=share_data.user_id)

        # 临时返回客户端IP用于整段cdn问题
        #client_ip_address = request.META.get("REMOTE_ADDR", None)

        is_admin = False
        if request.user.is_authenticated() and request.user.is_admin:
            is_admin = True

        return render_to_response('share/detail-full.jinja', {
            'supplier_data': supplier_data,
            'share': share_data,
            'edit_enable': edit_enable,
            'images': images_result,
            'keyword': keyword,
            'cover_data': cover_data,
            'origin': origin_data,
            'guess_data': guess_data,
            'is_admin': is_admin,
            #'client_ip_address': client_ip_address
        }, context_instance=RequestContext(request, processors=[site_info]))


#分享到微信
def share_to_weixin(request):
    share_id = request.GET.get('sid')
    image_id = request.GET.get('mid')
    post_data = None
    post_url = ''

    if share_id:
        post_data = ShareApi.check_data(share_id)
        if post_data:
            post_url = 'share/detail/all/%s/' % share_id
    if image_id:
        post_data = AttachApi.check_data(image_id).share_post
        if post_data:
            post_url = 'share/detail/%s/?mid=%s' % (post_data.id, image_id)

    if not post_data:
        return HttpResponseRedirect('/')

    return render_to_response('share/share-to-weixin.jinja', {
        'post_data': post_data,
        'post_url': post_url
    }, context_instance=RequestContext(request, processors=[site_info]))